<script setup>
	import {
		navigateBack,
		navigateToUpToRechargeRecord,
	} from "@/assets/scripts/navigate.js"
	import {
		rechargeConfigurationApi,
	} from "@/assets/api/other/recharge.js"
	import {
		ref,
		onMounted,
		onActivated,
	} from "vue";
	import {
		rechargeApi,
	} from '@/assets/api/other/recharge.js'
	import {
		hex_md5
	} from "@/assets/scripts/md5.js"
	import {
		h5Title,
		apiKey,
		appid,
	} from "@/config/index.js"
	import {
		getInfo2Api,
	} from "@/assets/api/other/recommend.js"

	const current = ref(0)
	const userInfo = ref({})
	const prepayId = ref("")
	const rechargeConfigurationList = ref([])

	const handleClick = (index) => {
		current.value = index
	}

	function generateSignature(params, key) {
		// 对参数按照参数名ASCII码从小到大排序
		const sortedKeys = Object.keys(params).sort();
		const sortedParams = {};
		sortedKeys.forEach(key => {
			sortedParams[key] = params[key];
		});

		// 将参数拼接成字符串
		let paramString = '';
		for (const key in sortedParams) {
			if (sortedParams[key]) { // 如果参数的值为空不参与签名
				paramString += `${key}=${sortedParams[key]}&`;
			}
		}
		paramString += `key=${key}`; // 拼接API密钥

		// 签名算法
		return hex_md5(paramString).toString().toUpperCase();;
	}

	const onBridgeReady = () => {
		const appId = appid
		const timeStamp = parseInt(new Date().getTime() / 1000) + ''
		const nonceStr = timeStamp + 'A' + timeStamp + 'B' + timeStamp
		const packageValue = "prepay_id=" + prepayId.value
		const signType = "MD5"

		// 示例用法
		const params = {
			appId,
			timeStamp,
			nonceStr,
			"package": packageValue,
			signType
		}
		const paySign = generateSignature(params, apiKey)

		WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				"appId": appId, //公众号ID，由商户传入     
				"timeStamp": timeStamp, //时间戳，自1970年以来的秒数     
				"nonceStr": nonceStr, //随机串     
				"package": packageValue,
				"signType": signType, //微信签名方式：     
				"paySign": paySign //微信签名 
			},
			function(res) {
				if (res.err_msg == "get_brand_wcpay_request:ok") {
					// 使用以上方式判断前端返回,微信团队郑重提示：
					//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					uni.showToast({
						title: '充值成功',
						icon: 'success',
						success: () => {
							userInfo_init() // 用户信息
							rechargeConfigurationList_init()
						}
					})
				}
			});
	}

	const handleRecharge = async () => {
		const res = await rechargeApi({
			rcAmount: 0.01,
			rcNum: 1000,
			rcGiveAwayNum: 10,
			rechargeConfigurationId: rechargeConfigurationList.value[current.value].id
		})
		if (res.code === 200) {
			console.log(res);
			prepayId.value = res.data.prepay_id
			if (typeof WeixinJSBridge == "undefined") {
				if (document.addEventListener) {
					document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
				} else if (document.attachEvent) {
					document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
					document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
				}
			} else {
				onBridgeReady();
			}
		} else {
			uni.showModal({
				title: '温馨提示',
				content: res.msg || JSON.stringify(res),
				confirmText: '关闭'
			})
		}
	}

	onMounted(() => {
		userInfo_init() // 用户信息
		rechargeConfigurationList_init()
	})

	onActivated(() => {
		rechargeConfigurationList_init()
	})

	const userInfo_init = async () => {
		const user = uni.getStorageSync('user')
		const res = await getInfo2Api(user.userId)
		if (res.code === 200) {
			userInfo.value = res.user
			uni.setStorageSync('user', res.user)
		} else {
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'error',
			})
		}
	}

	const rechargeConfigurationList_init = async () => {
		const res = await rechargeConfigurationApi()
		if (res.code === 200) {
			rechargeConfigurationList.value = res.rows
		}
	}
</script>

<template>
	<uv-navbar :fixed="false" bgColor="#f8f8f8" @leftClick="navigateBack" title="充值">
		<template #right>
			<view class="integral-btn" @click="navigateToUpToRechargeRecord">
				充值记录
			</view>
		</template>
	</uv-navbar>

	<view class="banner px-normal">
		<view class="bg-orgin"></view>
		<view class="p-normal color-white font-fs20">
			余额: {{userInfo.commemorativeCoin||0}} 缅怀币
		</view>
	</view>

	<view class="px-normal">
		<view class="bg-white p-normal borr-8 boxs">
			<view class="color-303133 font-fs20">
				余额充值
			</view>

			<view class="list">
				<uv-empty mode="list" icon="empty-favor" v-if="!rechargeConfigurationList.length"></uv-empty>
				<uv-grid :border="false" col="2" class="mt-normal ">
					<uv-grid-item v-for="(item,index) in rechargeConfigurationList" :key="index" class="p-small">
						<view class="item" @click="handleClick(index)">
							<view class="d-flex d-flex-aic d-flex-jcsb">
								<view class="font-fs12">
									套餐{{index+1}}
								</view>
								<uni-icons type="checkbox-filled" v-if="current == index" color="#19bd6b"
									size="20"></uni-icons>
								<uni-icons type="circle" v-else color="#dbdbdb" size="20"></uni-icons>
							</view>
							<view class="tac font-fs18 font-wb">
								充值{{item.rcAmount}}元
							</view>
							<view class="tac font-fs14 color-orgin mt-small">
								共获得{{parseInt(item.rcGiveAwayNum) + parseInt(item.rcNum)}}缅怀币
							</view>
							<view class="tac font-fs12 color-grey mt-small">
								{{h5Title}} ({{item.rcGiveAwayNum?`赠送了${item.rcGiveAwayNum}个缅怀币`:'无赠送'}})
							</view>
						</view>
					</uv-grid-item>
				</uv-grid>
			</view>

		</view>
	</view>

	<view class="p-big ">
		<view class="font-wb color-grey">
			充值说明
		</view>
		<view class="mt-small color-888888">
			充值后金额立即到账
		</view>
	</view>

	<view class="bottom-btn-height"></view>
	<view class="bottom-btn bottom-btn-height">
		<view class="d-flex d-flex-aic">
			<view class="">
				充值金额:
			</view>
			<view class="color-orgin">
				{{rechargeConfigurationList.length?rechargeConfigurationList[current].rcAmount:0}}
			</view>
			<view class="">
				元
			</view>
		</view>
		<uv-button class="borr-8 mt-small" color="linear-gradient(#fa6d5d, #fd906d)" text="立即充值"
			@click="handleRecharge"></uv-button>
	</view>
</template>

<style lang="scss" scoped>
	.tac {
		text-align: center;
	}

	.color-888888 {
		color: #888888;
	}

	.color-grey {
		color: #666666;
	}

	.color-orgin {
		color: #fa6d5d;
	}

	.bgc-orgin {
		background-image: linear-gradient(#fa6d5d, #fd906d);
	}

	.integral-btn {
		color: #12b886;
	}

	.color-303133 {
		color: #303133;
	}

	.borr-8 {
		overflow: hidden;
		border-radius: 12px;
	}

	.banner {
		position: relative;

		.bg-orgin {
			background-image: linear-gradient(#fa6e5d, #fd8a65);
			height: 160px;
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			z-index: -1;
		}
	}

	.color-white {
		color: #fff;
	}

	.boxs {
		box-shadow: 0 0 7px 0px #00000040;

		.list {
			min-height: 100px;
		}
	}

	.item {
		width: 100%;
		border: 1px solid #dddddd;
		border-radius: 4px;
		padding: 6px;
		box-sizing: border-box;
		overflow: hidden;
		height: 120px;
	}

	.bottom-btn-height {
		// height: 60px;
	}

	.bottom-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		min-width: 320px;
		max-width: 375px;
		margin: auto;
		// height: 60px;
		box-shadow: 0 0 7px 0px #00000040;
		background-color: #fff;
		padding: 10px 20px;
	}
</style>